﻿using CZBK.ShopHeima2.IDAL;
using CZBK.ShopHeima2.Model;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity.Utilities;

namespace CZBK.ShopHeima2.DAL
{
    public class BaseRepository<T>
        where T : class,new()
    {
        DbContext db = DbContextFactory.CreateDbContext();

        #     region 查询和分页
        public IEnumerable<T> LoadAllEntities(Func<T, bool> whereLambda)
        {
            return db.Set<T>().Where(whereLambda);
        }

        public IEnumerable<T> LoadAllPageEntities<S>(int pageIndex, int pageSize, Func<T, bool> whereLambda, Func<T, S> orderByLambda, bool isAsc)
        {
            var list = db.Set<T>().Where<T>(whereLambda);
            if (isAsc)
            {
                list = list.OrderBy(orderByLambda)
                    .Skip((pageIndex - 1) * pageSize)
                    .Take(pageSize);
            }
            else
            {
                list = list.OrderByDescending(orderByLambda)
                 .Skip((pageIndex - 1) * pageSize)
                 .Take(pageSize);
            }
            return list;
        }
        #endregion

        #region cud
        public T AddEntity(T entity)
        {
            db.Set<T>().Add(entity);
            return entity;
        }

        public bool UpdateEntity(T entity)
        {
            db.Entry<T>(entity).State = System.Data.Entity.EntityState.Modified;
            return true;
        }

        public bool DeleteEntity(int id)
        {
            db.Set<T>().Remove(db.Set<T>().Find(id));

            return true;
        }

        #endregion
    }
}
